let start = document.querySelector(".start") //开始预约
let name = document.querySelector(".name")//姓名框
let phone = document.querySelector(".phone")//电话框
let card = document.querySelector(".card")//身份证框
let login = document.querySelector(".login") //登录页面
let appointment = document.querySelector(".appointment") //预约页面
let data = document.querySelector("#data") //日期选中
let list_ul = document.querySelector(".list ul") //预约时间
let myAppoint = document.querySelector(".myAppoint")//我的预约
let myBooking = document.querySelector(".myBooking")//我的预约页面
let record = document.querySelector(".record")//预约记录
let invitation = document.querySelector(".invitation")//邀请函
let booking =document.querySelector(".booking")//开始预约到预约记录
let booking_back = document.querySelector(".booking-back")//预约记录返回开始预约
let login_back = document.querySelector(".login-back")//开始预约返回首页
//url
// let domain = 'http://192.168.31.97:7002'
let domain = 'http://shopback.bluej.cn'

let api = {
    register: domain+'/api/f_user/register',
    chooselist: domain+'/api/f_user/chooselist',
    chooseday:domain+ '/api/f_user/chooseday',
    bookday: domain+'/api/f_user/bookday',
    report:domain+'/api/f_user/report',
    Qrcode:domain+'/api/f_user/Qrcode'
}
//日期控件
function datatime(time) {
    let timehtml ="";
    time.forEach(el => {
        timehtml +=`<option>${el.day_time}</option>`
    });
    data.innerHTML =  timehtml
}
//日期时间选择
data.addEventListener("change", (e) => {
    daytime(e.target.value)
})
//显示场次 && 点击预约
async function daytime(day_time) {
    let listDay = await ajax({
        url: api.chooseday,
        method: "GET",
        params: {
            token: localStorage.token,
            day_time
        }
    })
    console.log(listDay.result.list);
    let day_list = ""
    listDay.result.list.forEach(el => {
        day_list += `<li>
                    <div>${el.show_name}</div><div class="reserved" data-date=${el.day_time} data-showid=${el.show_id}>可预约</div>
                    </li>`
        list_ul.innerHTML = day_list
    })
    let reserved = document.querySelectorAll(".reserved") //预约按钮
    reserved.forEach(el => {
        //点击预约
        el.addEventListener("click", async () => {
            console.log(event.target.dataset);
            let day_time = event.target.dataset.date;
            let show_id = event.target.dataset.showid;
            let bookDay = await ajax({
                url: api.bookday,
                method: "POST",
                params: {
                    token: localStorage.token,
                    day_time,
                    show_id,
                }
            })
            if (bookDay.msg=="操作成功") {
                el.innerText="已预约"
                el.style.color="red"
            }
           
        })
    })

}
//日期格式化
Date.prototype.format =function(format){
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate()+1, //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (this.getFullYear()+"").substr(4- RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length==1? o[k] :
                ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
}
function dateFormaterYMD(value){
    if(value){
        return new Date(value).format('yyyy年MM月dd日');
    }else{
        return value='';
    }
}

//输入正则
let reg_name = /^[\u4e00-\u9fa5]{0,}$/;
let reg_phone = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
let reg_card = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
//输入判断
function judge() {
     // 姓名判断
     if(!reg_name.test(name.value)||name.value==""){
        name.value="";
        name.placeholder="请输入汉字";
        name.style.border="1px solid red"
    }else{
        name.style.border=""
    }
    //手机判断
    if(!reg_phone.test(phone.value)){
         phone.value="";
         phone.placeholder="手机错误";
         phone.style.border="1px solid red"
     }else{
         phone.style.border=""
     }
    //  身份证判断
   if(!reg_card.test(card.value)){
       card.value="";
       card.placeholder="身份证错误";
       card.style.border="1px solid red"
   }else{
        card.style.border=""
 }

}
//开始预约
start.addEventListener("click", async () => {
    judge();
    if (!reg_name.test(name.value)|| name.value=="" ||!reg_phone.test(phone.value)||!reg_card.test(card.value)) {
        return
   }
    await ajax({
        url: api.register,
        method: "POST",
        params: {
            name: name.value,
            phone: phone.value,
            card: card.value
        }
        // params: {
        //     name: "老李",
        //     phone: "13612345688",
        //     card:"440583199802111878"
        // }

    }).then(async (res) => {
        console.log("登录接口", res)
        let token = res.result.token;
        if (name.value != "" && phone.value != "") {
            console.log(1);
            let name_v = name.value;
            let phone_v = phone.value;
            localStorage.setItem("name", name_v);
            localStorage.setItem("phone", phone_v);
        }
        console.log(res.result)
        // 将 token 存至 storage 供后续使用
        localStorage.setItem("token", token);

        login.style.display = "none";
        appointment.style.display = "block";
        let listData = await ajax({
            url: api.chooselist,
            method: "GET",
            params: {
                token
            }
        })
        console.log("日期", listData.result.list)
        datatime(listData.result.list)
        let day_time = listData.result.list.day_time;
        daytime(data.value)

    })
})
//我的预约
myAppoint.addEventListener("click", async () =>{
    judge();
    if (!reg_name.test(name.value)|| name.value=="" ||!reg_phone.test(phone.value)||!reg_card.test(card.value)) {
        return
    }
    await ajax({
        url: api.report,
        method: "POST",
        params: {
            name: name.value,
            phone: phone.value,
        }
        // params: {
        //     name: "老李",
        //     phone: "13612345688"
        // }
    }).then(res=>{
        login.style.display = "none";
        myBooking.style.display = "block";
        invitationCard(res)
    })
})
//开始预约->我的预约
booking.addEventListener("click",async ()=>{
    await ajax({
        url: api.report,
        method: "POST",
        params: {
            name: localStorage.name,
            phone: localStorage.phone
        }
    }).then(res=>{
        appointment.style.display = "none"
        myBooking.style.display = "block";
        invitationCard(res)
    })
})
//我的预约->开始预约
booking_back.addEventListener("click",async ()=>{
    myBooking.style.display = "none";
    appointment.style.display = "block";
    // login.style.display = "block";
    let listData = await ajax({
        url: api.chooselist,
        method: "GET",
        params: {
            token:localStorage.token
        }
    })
    datatime(listData.result.list)
    let day_time = listData.result.list.day_time;
    daytime(data.value)
})
//开始预约->登录
login_back.addEventListener("click",()=>{
    appointment.style.display = "none";
    login.style.display = "block";
})
//邀请函
function invitationCard(data) {
    let record_html="";
    let count=0;
    if (data.result.length>0) {
        data.result.forEach((el,idx)=>{
            record_html += `<div class="recordBox" data-id="${el.id}" data-name="${el.name}"  data-time="${el.day_time}">
                            <p data-id="${el.id}" data-name="${el.name}"  data-time="${el.day_time}">姓名：${el.name}</p>
                            <p data-id="${el.id}" data-name="${el.name}"  data-time="${el.day_time}">场次：${el.day_time}</p>
                            </div>`;

        })
        record.innerHTML=record_html; 
    }
    console.log(data);
    let recordBox = document.querySelectorAll(".recordBox");
    recordBox.forEach(el=>{
        el.addEventListener("click",async (event)=>{
            console.log(event.target);
            myBooking.style.display = "none";
            invitation.style.display= "block";
            let  data_name = event.target.dataset.name;
            let data_time = event.target.dataset.time
            let Qrc = await ajax({
                url: api.Qrcode,
                method: "GET",
                params: {
                    token: localStorage.token,
                    id: event.target.dataset.id
                }
            }) 
            let data1 = dateFormaterYMD(data_time)
            console.log(data1);   
            console.log(data_time);  
            invitation.innerHTML=`
            <div class="invitation-top">
                <h3>${data_name}:</h3><div class="invitation-back">Back</div>
            </div>
            <p> 欢迎您在 ${data1} 10:00 参观2019广州国际
                花卉艺术展暨中国插花花艺展。</p>
                <div class="QR">
                    <img src="${Qrc.data.data}" alt="">
                </div>
                <div>
                    <button>保存图片</button>

                </div>
                <p>请保存此页面，进入参观区域前向工作人员
            出示，谢谢！</p>
            `
            console.log(Qrc.data.data);
            let invitation_back = document.querySelector(".invitation-back")
            invitation_back.addEventListener("click",()=>{
                invitation.style.display= "none";
                myBooking.style.display = "block";
            })
        })
    })
}
